import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:nc_demo/base/network/api_request.dart';

import '../login/login_page.dart';
import '../scan/continue_scan_example.dart';
import '../scan/scanner_page.dart';
import '../util/host_manager.dart';

///
/// ProjectName: nc_demo
/// Author: lizhi
/// CreateDate: 2025/3/20 17:39
/// Copyright: ©2025 NEW CORE Technology Co. Ltd. All rights reserved.
/// Description: 代码文件说明，markdown 格式
///
Future pushHome(BuildContext context, {Map<String, dynamic>? userInfo}) {
  return Navigator.of(context).pushReplacement(MaterialPageRoute(
    settings: const RouteSettings(name: 'MainPage'),
    builder: (context) => MainPage(
      userInfo: userInfo,
    ),
  ));
}

class MainPage extends StatefulWidget {
  const MainPage({super.key, this.userInfo});

  final Map<String, dynamic>? userInfo;

  @override
  State<MainPage> createState() => _MainPageState();
}

class _MainPageState extends State<MainPage> {
  @override
  void initState() {
    initApiHost();
    super.initState();
  }

  /// 初始设置网络请求域名
  void initApiHost() async {
    Api.shareInstance().addHeader({'agent': 'APP'});
    var host = await NDHostManager.currentHost;
    await Api.shareInstance().setHost(host);
  }

  void _showExitDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('确认退出'),
          content: Text('你确定要退出应用吗？'),
          actions: <Widget>[
            TextButton(
              child: Text('取消'),
              onPressed: () {
                // 关闭对话框
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text('确定'),
              onPressed: () {
                // 在Android上可以调用如下方法来关闭应用：
                if (defaultTargetPlatform == TargetPlatform.android) {
                  SystemNavigator.pop();
                } else {
                  // 对于iOS等其他平台，退出应用的行为可能需要另行处理或不支持直接退出
                  // 通常情况下，iOS不允许从应用内部直接退出应用
                  exit(0); // 注意：在Flutter中使用exit函数强制退出应用并不是最佳实践
                }
                Navigator.of(context).pop(true); // 返回true表示同意退出
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        // 当用户点击返回按钮时显示退出确认对话框
        _showExitDialog(context);
        // 返回false以阻止默认的返回行为
        return Future.value(false);
      },
      child: Scaffold(
        body: SafeArea(
          child: SizedBox(
            width: double.maxFinite,
            child: Column(
              children: [
                const SizedBox(height: 80),
                const Text('首页'),
                Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Text('用户信息：${widget.userInfo}'),
                ),
                const SizedBox(height: 8),
                FilledButton(
                  onPressed: () {
                    /// 点击跳转登录页
                    LoginPage.push(context);
                  },
                  child: const Text('登录'),
                ),
                const SizedBox(height: 16),
                FilledButton(
                  onPressed: () {
                    /// 点击跳转扫码页
                    ScannerPage.push(context);
                  },
                  child: const Text('摄像头扫码'),
                ),
                const SizedBox(height: 16),
                FilledButton(
                  onPressed: () {
                    /// 点击跳转扫码页
                    ContinueScanExample.push(context);
                  },
                  child: const Text('连续扫码（摄像头模式）'),
                ),
                const SizedBox(height: 16),
                FilledButton(
                  onPressed: () {
                    /// 点击跳转扫码页
                    ContinueScanExample.push(context, isPDAModel: true);
                  },
                  child: const Text('连续扫码（激光扫码模式）'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
